import com.google.appengine.api.datastore.*
import static com.google.appengine.api.datastore.FetchOptions.Builder.*

def latestSnippets = []

if ('latestSnippets' in memcache) {
	latestSnippets = memcache['latestSnippets']
} else {
	def query = new Query("Snippet")
	query.addSort("createdDate", Query.SortDirection.DESCENDING)
	PreparedQuery preparedQuery = datastore.prepare(query)
	latestSnippets = preparedQuery.asList( withLimit(10) )
	memcache['latestSnippets'] = latestSnippets 
}

def getSnippetCreationDetail(snippet) {
 "posted " + (snippet.createdDate !=null ? new com.ocpsoft.pretty.time.PrettyTime().format(snippet.createdDate) : "") + " by "
}

def getSnippetAuthorDetail(snippet) {
 snippet.author instanceof com.google.appengine.api.users.User ? snippet.author.nickname : "anonymous"
}

html.html {
	body {

		ul(class:"yui-g x-snippetr-actions") {
			li { a(href:"/", "New Snippet") }
		}

		ul(class:"yui-g") {
			latestSnippets.each { snippet -> li { 
						a(href:"/snippet/${snippet.key.id}", snippet.name)
						small(getSnippetCreationDetail(snippet)) { em (class:"snippetAuthorName", getSnippetAuthorDetail(snippet))  } 
				} 
			}
		}
	}

}